const Koa = require('koa')
const app = new Koa()
const api = require('./routes/api')
const web = require('./routes/web')
const bodyParser = require('koa-bodyparser')
const Logger = require('koa-logger')
const Static = require('koa-static');
const session = require('koa-session')

const Mongo = require('./app/Lib/mongoose')

app.keys = ['this is app session keys for mankong siwi test']

const session_config = {
	key: 'koa:sess',
	maxAge: 86400000,
	overwrite: true,
	httpOnly: true,
	signed: true,
	rolling: false,
  };
// 全局错误处理
app.use(async (ctx, next) => {
	try {
		await next()
	} catch (err) {
		ctx.body = err.message
		ctx.status = err.status || 500
	}
})

//静态目录
app.use(Static(__dirname + '/public'))

// session
app.use(session(session_config, app))

// Mongodb 链接全局
try {
	Mongo.connect
	console.log('Mongodb 已经连接')
} catch (error) {
	console.trace(error)
}


app.use(Logger())
app.use(bodyParser())
app.use(api.routes())
app.use(web.routes())
app.listen(3001, () => {
	console.log('the app is running at 3000 port')
})



module.exports = app